package com.tuxing.draa_data.util.easyExcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
//import com.alibaba.fastjson.JSON;
import com.tuxing.draa_data.dto.EsiJournalExcelDto;
import com.tuxing.draa_data.service.subject.SubjectService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author yuanshihang
 * @version 1.0
 * @className EsiJournalDataListener
 * @description 基础描述: esi核心期刊表格解析器
 * @date 2021/12/29 9:51
 */
@Slf4j
public class EsiJournalDataListener implements ReadListener<EsiJournalExcelDto> {

    private SubjectService subjectService;

    public SubjectService getSubjectService() {
        return subjectService;
    }

    public EsiJournalDataListener setSubjectService(SubjectService subjectService) {
        this.subjectService = subjectService;
        return this;
    }

    public EsiJournalDataListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    /**
     * 每隔1000条存储数据库，实际使用中可以1000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;

    /**
     * 缓存的数据
     */
    private List<EsiJournalExcelDto> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(EsiJournalExcelDto esiJournalExcelDto, AnalysisContext analysisContext) {
//        log.info("解析接收一条数据：" + JSON.toJSONString(esiJournalExcelDto));
        cachedDataList.add(esiJournalExcelDto);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            //释放内存
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        /*
        在解析最后的数据时可能造成不足1000条无法进行保存的问题，该方法就是对最后的余量
        数据进行保存
         */
        saveData();
    }

    private void saveData() {
        subjectService.esiJournalParse(cachedDataList);
    }
}
